package at.fhooe.mcm12.java.sensors;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;

import at.fhooe.mcm12.java.enums.OutputFormat;
import at.fhooe.mcm12.java.enums.SensorType;
import at.fhooe.mcm12.java.interfaces.RMISensorInterface;
import at.fhooe.mcm12.java.sensors.data.SensorValue;
import at.fhooe.mcm12.java.serializer.SensorSerializer;

/**
 * 
 * @author Michael Schoellhammer
 *
 */
public abstract class AbstractSensor extends UnicastRemoteObject implements RMISensorInterface, Serializable{


	protected String m_name;
	protected SensorType m_sensorType;
	protected String m_description;
	protected SensorValue m_dataType;
	
	protected SensorSerializer m_serializer;
	protected boolean m_isSubscribable;
	protected boolean m_active;
		
	protected AbstractSensor() throws RemoteException {
		super();
		m_name = getClass().getSimpleName();
		initiateRMIServer();
	}
	
	protected void initiateRMIServer() {
		try {

			if (System.getSecurityManager() == null) {
				System.setProperty("java.security.policy", "file:./res/rmi.policy");
				System.setSecurityManager(new SecurityManager());
			}
			
			UnicastRemoteObject.unexportObject(this, true);

			RMISensorInterface stub = (RMISensorInterface) UnicastRemoteObject.exportObject(this,
					0);
//			Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);

			LocateRegistry.getRegistry().rebind(this.getClass().getSimpleName(), stub);
			System.out.println("Registered: " + this.getClass().getSimpleName() + " -> "
					+ this.getClass().getName() + "[" + this + "]");

		} catch (Exception _e) {
			_e.printStackTrace();
		}
	}
	
	public abstract void serialize(OutputFormat _format, SensorValue _value);
	
	@Override
	public String getName()
	{
		return m_name;
	}
	
	@Override
	public void setName(String _name)
	{
		m_name = _name;
	}
	
	@Override
	public SensorType getSensorType()
	{
		return m_sensorType;
	}
	
	@Override
	public void setSensorType(SensorType _sensorType)
	{
		m_sensorType = _sensorType;
	}
	
	@Override
	public String getDescription()
	{
		return m_description;
	}
	
	@Override
	public void setDescription(String _description)
	{
		m_description = _description;
	}
	
	@Override
	public SensorValue getDataType()
	{
		return m_dataType;
	}
	
	@Override
	public void setDataType(SensorValue _dataType)
	{
		m_dataType = _dataType;
	}
	
	@Override
	public boolean isActive()
	{
		return m_active;
	}
	
	@Override
	public void setActive(boolean _active)
	{
		m_active = _active;
	}
	
	@Override
	public boolean isSubscribable()
	{
		return m_isSubscribable;
	}
	
	@Override
	public void setSubscribable(boolean _subscribable)
	{
		m_isSubscribable = _subscribable;
	}
	
	public String toString()
	{
		return getName();
	}
}
